package advance.juc;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class AQSPractice extends AbstractQueuedSynchronizer {

    @Override
    protected boolean tryAcquire(int arg) {
        // 使用 compareAndSetState 控制 AQS 中的同步变量
        if (compareAndSetState(0, 1)) {
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryReleaseShared(int arg) {
        setExclusiveOwnerThread(null);
        setState(0);
        return true;
    }

    public void lock() {
        acquire(1);
    }

    public boolean tryLock() {
        return tryAcquire(1);
    }

    public void unlock() {
        release(1);
    }

    public static void main(String[] args) throws InterruptedException {
        final AQSPractice lock = new AQSPractice();
        lock.lock();

        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    System.out.println(Thread.currentThread().getId() + " acquired the lock!");
                    lock.unlock();
                }
            }).start();
            Thread.sleep(10);
        }
        System.out.println("main thread unlock!");
        lock.unlock();
    }
}
